<?php


namespace app\controllers;


use app\components\BaseAuthController;
use yii\base\Exception;
use yii\data\ArrayDataProvider;
use yii\helpers\FileHelper;

class FileController extends BaseAuthController {

    public $name = '文件';

    public function actionIndex() {
        $path = FILE_ROOT;
        try {
            FileHelper::createDirectory($path);
        } catch (Exception $e) {
        }

        $files = FileHelper::findFiles($path);
        $data = [];
        foreach ($files as $file) {
            $data[] = ['name' => basename($file)];
        }
        $dataProvider = new ArrayDataProvider(['allModels' => $data]);
        return $this->render(compact('dataProvider'));
    }

    public function actionView() {
        $id = $this->get('id');
        $path = FILE_ROOT . '/files';
        $files = FileHelper::findFiles($path);
        if (isset($files[$id])) {
            $data = file_get_contents($files[$id]);
            $data = str_replace("\n", "<br>", $data);
            return $data;
        }
        return '文件不存在';
    }
}